﻿using System;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Web;

namespace Com.Core.Helps
{
    public class ImageUploadHelper
    {

        public static string Upload(string imgData, string filepath = "")
        {
            if (string.IsNullOrEmpty(imgData)) return "";
            filepath = "/UploadFile/Images/" + (!string.IsNullOrEmpty(filepath) ? filepath.Trim('/') + "/" : "");
            try
            {
                var array = imgData.Split(',');
                imgData = array[1];
                var imgType = array[0].Split('/')[1];

                var fileExtent = imgType.Split(';')[0];
                string[] temp = { "jpg", "jpeg", "png", "gif" };
                if (!temp.Contains(fileExtent)) return "只能上传jpg,jpeg,png,gif格式的图片";
                byte[] bytes = Convert.FromBase64String(imgData);
                if (!CheckExtension(bytes)) return "只能上传jpg,jpeg,png,gif格式的图片!";

                string str;
                using (MemoryStream ms = new MemoryStream(bytes))
                {
                    using (Bitmap bmp = new Bitmap(ms))
                    {
                        string filePath = filepath.TrimEnd('/') + "/" + DateTime.Now.ToString("yyyy-MM-dd") + "/";
                        string fileName = Guid.NewGuid() + "." + fileExtent;
                        string realPath = HttpContext.Current.Server.MapPath(filePath);
                        if (!Directory.Exists(realPath)) Directory.CreateDirectory(realPath);
                        string fullPath = realPath + fileName;
                        bmp.Save(fullPath);
                        str = filePath + fileName;
                    }
                }
                return str;
            }
            catch
            {
                //throw new Exception(e.Message);
                return "上传失败";
            }
        }

        public static bool CheckExtension(byte[] bytes)
        {
            MemoryStream ms = new MemoryStream(bytes);
            BinaryReader br = new BinaryReader(ms);
            bool flag = false;
            try
            {
                var buffer = br.ReadByte();
                var fileclass = buffer.ToString();
                var temp = int.Parse(fileclass);
                var t = Enum.IsDefined(typeof(ImageExtension), temp);
                if (t) flag = true;
            }
            catch
            {
                flag = false;
            }
            finally
            {
                ms.Close();
                br.Close();
            }
            return flag;
        }
    }
}
